<template>
  <div>
    <Category :disable="showIndex !== 1"></Category>
    <SpuList
      v-if="showIndex === 1"
      @changeShowIndex="changeShowIndex"
    ></SpuList>
    <SpuInfo
      @changeShowIndex="changeShowIndex"
      v-else-if="showIndex === 2"
      :spuInfo="spuInfo"
    ></SpuInfo>
    <SkuInfo
      v-else
      :spuInfo="spuInfo"
      @changeShowIndex="changeShowIndex"
    ></SkuInfo>
  </div>
</template>

<script lang="ts">
  import { defineComponent } from "vue"

  export default defineComponent({
    name: "Spu",
  })
</script>

<script setup lang="ts">
  import { ref } from "vue"
  import SpuList from "./components/SpuList.vue"
  import SpuInfo from "./components/SpuInfo.vue"
  import SkuInfo from "./components/SkuInfo.vue"
  import type { spuInfoItemType } from "@/api/spu"
  import useCategoryStore from "@/stores/category"
  import { storeToRefs } from "pinia"

  //获取categoryStore数据对象
  const categoryStore = useCategoryStore()

  //从store中获取当前的category3Id
  const { category3Id } = storeToRefs(categoryStore)

  //定义一个数据保存当前展示的组件
  //1:代表SpuList  2：代表SpuInfo  3：代表SkuInfo
  const showIndex = ref(1)

  //在父组件中初始化一个数据 ,把这个数据传递给子组件SpuInfo
  //如果是新增,则传递的就是这个初始化空数据
  //如果是修改,则在下边的事件中会把这个spuInfo修改为回填的数据
  const spuInfo = ref<spuInfoItemType>({
    spuName: "",
    description: "",
    category3Id: category3Id.value as number,
    tmId: null,
    spuSaleAttrList: [],
    spuImageList: [],
  })

  //定义一个自定义事件 切换组件
  const changeShowIndex = (index: number, row?: spuInfoItemType) => {
    showIndex.value = index

    //因为初始化数据中无法拿到category3Id,所以在切换页面的时候,可以把3Id给赋值上
    spuInfo.value.category3Id = category3Id.value as number

    //如果点击的是修改按钮，则row参数就代表的是该行数据，然后就直接赋值给spuInfo
    if (row) {
      spuInfo.value = row
    } else {
      spuInfo.value = {
        spuName: "",
        description: "",
        category3Id: category3Id.value as number,
        tmId: null,
        spuSaleAttrList: [],
        spuImageList: [],
      }
    }
  }
</script>

<style scoped lang="scss"></style>
